/**
 * @file Aplicacion.java
 * Clase para la interfaz principal de la Aplicación
 * 
 * @author Carlos Rabelo
 * @version 1.2
 */
package Controlador;

import Controladores.*;
import Interfaz.*;
import Interfaz.InterfazEquipo;
import GestorJugadores.*;
import GestorUsuarios.*;
import GestorEquipos.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class Aplicacion extends javax.swing.JFrame {

    private InterfazJugador interfaz_jugador = null;
    private InterfazEquipo interfaz_equipo = null;
    private InterfazUsuario interfaz_usuario = null;
    private Usuario usuarioActivo = null;
    private Boolean es_gestor;
    
    /**
     * Constructor por defecto
     * @param void
     * @return void
     */
    public Aplicacion() {
        super("FCB Granada");
        initComponents();
        jPanel_Principal.setVisible(false);
        jPanel_Desconectar.setVisible(false);
        this.pack();
    }

    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel_Desconectar = new javax.swing.JPanel();
        BotonDesconectar = new javax.swing.JButton();
        Boton_MenuPrincipal = new javax.swing.JButton();
        jPanel_Login = new javax.swing.JPanel();
        BotonEntrar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        Texto_Usuario = new javax.swing.JTextField();
        Texto_Password = new javax.swing.JPasswordField();
        BotonLimpiar = new javax.swing.JButton();
        jPanel_Principal = new javax.swing.JPanel();
        BotonUsuarios = new javax.swing.JButton();
        BotonJugadores = new javax.swing.JButton();
        BotonEquipos = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(200, 100));
        getContentPane().setLayout(new java.awt.FlowLayout());

        jPanel_Desconectar.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        BotonDesconectar.setText("Desconectar");
        BotonDesconectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonDesconectarActionPerformed(evt);
            }
        });

        Boton_MenuPrincipal.setText("Menu Principal");
        Boton_MenuPrincipal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Boton_MenuPrincipalActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel_DesconectarLayout = new javax.swing.GroupLayout(jPanel_Desconectar);
        jPanel_Desconectar.setLayout(jPanel_DesconectarLayout);
        jPanel_DesconectarLayout.setHorizontalGroup(
            jPanel_DesconectarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_DesconectarLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel_DesconectarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(Boton_MenuPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(BotonDesconectar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel_DesconectarLayout.setVerticalGroup(
            jPanel_DesconectarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_DesconectarLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(BotonDesconectar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Boton_MenuPrincipal)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel_Desconectar);

        jPanel_Login.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        BotonEntrar.setText("Entrar");
        BotonEntrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonEntrarActionPerformed(evt);
            }
        });

        jLabel1.setText("Usuario");

        jLabel2.setText("Contraseña");

        Texto_Usuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Texto_UsuarioActionPerformed(evt);
            }
        });

        BotonLimpiar.setText("Limpiar");
        BotonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonLimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel_LoginLayout = new javax.swing.GroupLayout(jPanel_Login);
        jPanel_Login.setLayout(jPanel_LoginLayout);
        jPanel_LoginLayout.setHorizontalGroup(
            jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_LoginLayout.createSequentialGroup()
                .addGroup(jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel_LoginLayout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addGroup(jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Texto_Usuario, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(Texto_Password, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel_LoginLayout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addComponent(BotonEntrar)
                        .addGap(18, 18, 18)
                        .addComponent(BotonLimpiar)))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        jPanel_LoginLayout.setVerticalGroup(
            jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_LoginLayout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addGroup(jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(Texto_Usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(Texto_Password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(jPanel_LoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BotonEntrar)
                    .addComponent(BotonLimpiar))
                .addContainerGap(100, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel_Login);

        jPanel_Principal.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        BotonUsuarios.setText("Gestion Usuarios");
        BotonUsuarios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonUsuariosActionPerformed(evt);
            }
        });

        BotonJugadores.setText("Gestion Jugadores");
        BotonJugadores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonJugadoresActionPerformed(evt);
            }
        });

        BotonEquipos.setText("Gestion Equipos");
        BotonEquipos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonEquiposActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel_PrincipalLayout = new javax.swing.GroupLayout(jPanel_Principal);
        jPanel_Principal.setLayout(jPanel_PrincipalLayout);
        jPanel_PrincipalLayout.setHorizontalGroup(
            jPanel_PrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_PrincipalLayout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(jPanel_PrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(BotonUsuarios)
                    .addComponent(BotonEquipos))
                .addGap(27, 27, 27)
                .addComponent(BotonJugadores)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel_PrincipalLayout.setVerticalGroup(
            jPanel_PrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_PrincipalLayout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(jPanel_PrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BotonUsuarios)
                    .addComponent(BotonJugadores))
                .addGap(31, 31, 31)
                .addComponent(BotonEquipos)
                .addContainerGap(112, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel_Principal);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BotonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonLimpiarActionPerformed
        // TODO add your handling code here:
        Texto_Usuario.setText("");
        Texto_Password.setText("");
    }//GEN-LAST:event_BotonLimpiarActionPerformed

    private void BotonEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonEntrarActionPerformed
        
         // Consultar el usuario
      
        usuarioActivo=null;
        try {
            usuarioActivo = ControladorUsuario.autentificarse(Texto_Usuario.getText(), new String(Texto_Password.getPassword()));
       } catch (Exception ex) {
            Logger.getLogger(Aplicacion.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //sesion_iniciada=true;
        if (usuarioActivo!=null) {
            jPanel_Login.setVisible(false);
            jPanel_Principal.setVisible(true);
            jPanel_Desconectar.setVisible(true);
            this.pack();
            // Lo siguiente lanza una excepción porque en el prototipo el usuario activo es null
            
            es_gestor=usuarioActivo.getEsGestor();
            
            
        } else {
            JOptionPane.showMessageDialog(null,"Usuario/Contraseña incorrectos.","Error", JOptionPane.ERROR_MESSAGE);
            
        }
        
        
    }//GEN-LAST:event_BotonEntrarActionPerformed

    private void BotonJugadoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonJugadoresActionPerformed
        /**
         * La interfaz crea una instancia la primera vez que se llama al get
         * Pongo esto aquí para que se cree la interfaz solo si el usuario la
         * necesita (puede que solo trabaje con equipos o usuarios
         */
        if (interfaz_jugador==null){
            interfaz_jugador=InterfazJugador.getInstancia();
            this.add(interfaz_jugador);
        }
        interfaz_jugador.inicializar(es_gestor);
        jPanel_Principal.setVisible(false);
        interfaz_jugador.setVisible(true);
        this.pack();
        ControladorJugador.getInstancia().inicializar();
    }//GEN-LAST:event_BotonJugadoresActionPerformed

    private void BotonDesconectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonDesconectarActionPerformed
        // TODO add your handling code here:
        int n=JOptionPane.showConfirmDialog(null, "¿Seguro que quieres salir?", "Atención", JOptionPane.YES_NO_OPTION);
        if (n==JOptionPane.YES_OPTION){
            jPanel_Login.setVisible(true);
            jPanel_Principal.setVisible(false);
            jPanel_Desconectar.setVisible(false);
            interfaz_jugador.setVisible(false);
            interfaz_equipo.setVisible(false);
            interfaz_usuario.setVisible(false);
            this.pack();
            this.usuarioActivo=null;
            this.Texto_Usuario.setText("");
            this.Texto_Password.setText("");
        }
    }//GEN-LAST:event_BotonDesconectarActionPerformed

    private void Boton_MenuPrincipalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Boton_MenuPrincipalActionPerformed
        // TODO add your handling code here:
        jPanel_Login.setVisible(false);
        jPanel_Principal.setVisible(true);
        jPanel_Desconectar.setVisible(true);
        if (interfaz_usuario!=null){
            interfaz_usuario.setVisible(false);
        }
        if (interfaz_jugador!=null){
            interfaz_jugador.setVisible(false);
        }
        if (interfaz_equipo!=null){
            interfaz_equipo.setVisible(false);
        }
        
        
        
        this.pack();
    }//GEN-LAST:event_Boton_MenuPrincipalActionPerformed

    private void BotonEquiposActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonEquiposActionPerformed
        if (interfaz_equipo==null){
            interfaz_equipo=InterfazEquipo.getInstancia();
            this.add(interfaz_equipo);
        }
        interfaz_equipo.limpiar(); // la última vez que se usó los campos puede que tuvieran contenido
        jPanel_Principal.setVisible(false);
        interfaz_equipo.setVisible(true);
        this.pack();
    }//GEN-LAST:event_BotonEquiposActionPerformed

    private void BotonUsuariosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonUsuariosActionPerformed
        if (interfaz_usuario==null){
            interfaz_usuario=InterfazUsuario.getInstancia();
            this.add(interfaz_usuario);
        }
        interfaz_usuario.limpiar(); // la última vez que se usó los campos puede que tuvieran contenido
        jPanel_Principal.setVisible(false);
        interfaz_usuario.setVisible(true);
        this.pack();
    }//GEN-LAST:event_BotonUsuariosActionPerformed

    private void Texto_UsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Texto_UsuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_Texto_UsuarioActionPerformed

    
   public String GetTextLogin(){
       return  Texto_Usuario.getText();
   }
   
   public String GetTextPassword(){
       return  Texto_Password.getPassword().toString();
   }
         /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Aplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Aplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Aplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Aplicacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Aplicacion().setVisible(true);
            }
        });
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotonDesconectar;
    private javax.swing.JButton BotonEntrar;
    private javax.swing.JButton BotonEquipos;
    private javax.swing.JButton BotonJugadores;
    private javax.swing.JButton BotonLimpiar;
    private javax.swing.JButton BotonUsuarios;
    private javax.swing.JButton Boton_MenuPrincipal;
    private javax.swing.JPasswordField Texto_Password;
    private javax.swing.JTextField Texto_Usuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel_Desconectar;
    private javax.swing.JPanel jPanel_Login;
    private javax.swing.JPanel jPanel_Principal;
    // End of variables declaration//GEN-END:variables
}
